package org.kmp.project

import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue


interface INavElement {

    fun tag(): String

    @Composable
    fun screen()

    fun onResult(result: Any?) {}
}

enum class NavDirection { Forward, Backward }

object NavigationManager {

    data class Entry(
        val element: INavElement,
        val onResult: ((Any?) -> Unit)? = null
    )


    val stack = mutableStateListOf<Entry>()
    var direction by mutableStateOf(NavDirection.Forward)
        private set

    fun navigateTo(
        navElement: INavElement,
        onResult: ((Any?) -> Unit)? = null
    ) {
        direction = NavDirection.Forward
        stack.add(Entry(navElement, onResult))
    }

    fun navigateBack(result: Any? = null) {
        if (stack.size > 1) {
            direction = NavDirection.Backward
            val last = stack.removeAt(stack.lastIndex)
            result?.let {
                last.onResult?.invoke(it)
            }
        }
    }

    fun currentElement(): INavElement? = stack.lastOrNull()?.element

    fun isElementsEmpty(): Boolean=stack.isEmpty()
}

